import { IBreadcrumb } from "@/base-ui/bread";
import type { RouteRecordRaw } from "vue-router";

let firstMenu: any = "";
export function mapMenusToRoutes(UserMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = [];
  //1. 先去加载默认所有的routes
  const allRoutes: RouteRecordRaw[] = [];
  //require.context()是webpack的表达式
  const routeFiles = require.context("../router/main", true, /\.ts/);
  routeFiles.keys().forEach((key) => {
    const route = require("../router/main" + key.split(".")[1]);
    allRoutes.push(route.default);
  });
  console.log("allRoutes", allRoutes);

  //2. 再根据菜单获取需要的routes
  const recurseGetRoute = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type == 2) {
        const route = allRoutes.find((route) => route.path == menu.url);
        if (route) routes.push(route);
        if (!firstMenu) firstMenu = menu;
      } else {
        recurseGetRoute(menu.children);
      }
    }
  };
  recurseGetRoute(UserMenus);
  return routes;
}

export function pathMapBreadcrumbs(userMenus: any[], currentPath: string) {
  let breadcrumbs: IBreadcrumb[] = [];
  pathMapToMenu(userMenus, currentPath, breadcrumbs);
  return breadcrumbs;
}

export function pathMapToMenu(
  userMenus: any[],
  currentPath: string,
  breadcrumb?: IBreadcrumb[]
): any {
  for (const menu of userMenus) {
    if (menu.type == 1) {
      const findMenu = pathMapToMenu(menu.children, currentPath);
      if (findMenu) {
        breadcrumb?.push({ name: menu.name });
        breadcrumb?.push({ name: findMenu.name });
        return findMenu;
      }
    } else if (menu.type == 2 && menu.url == currentPath) {
      return menu;
    }
  }
}
export { firstMenu };

export function mapMenusToPermissions(userMenus: any[]) {
  const permissions: string[] = [];
  const _recurseGetPermission = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type == 1 || menu.type == 2) {
        _recurseGetPermission(menu.children ?? []);
      } else if (menu.type == 3) {
        permissions.push(menu.permission);
      }
    }
  };
  _recurseGetPermission(userMenus);
  return permissions;
}
export function menuMapLeafKeys(menuList: any[]) {
  const leftKeys: number[] = [];

  const _recurseGetLeaf = (menuList: any[]) => {
    for (const menu of menuList) {
      if (menu.children) {
        _recurseGetLeaf(menu.children);
      } else {
        leftKeys.push(menu.id);
      }
    }
  };
  _recurseGetLeaf(menuList);

  return leftKeys;
}
